#include "tcpserver.h"
#include <QDebug>

TcpServer::TcpServer(QObject *parent, int port) : QTcpServer(parent)
{
    listen(QHostAddress::Any, port);
}

void TcpServer::incomingConnection(qintptr socketDescriptor)
{
    qDebug() << "new conn, fd: " << socketDescriptor;

    // 当有一个新的客户端连接时，触发incomingConnection
    TcpClientSocket *tcpClientSocket = new TcpClientSocket(this);
    connect(tcpClientSocket, SIGNAL(updateClients(QString, int)), this, SLOT(updateClients(QString, int)));
    connect(tcpClientSocket, SIGNAL(disconnected(qintptr)), this, SLOT(onDisconnected(qintptr)));
    tcpClientSocket->setSocketDescriptor(socketDescriptor);
    tcpClientSocketList.append(tcpClientSocket);
}

void TcpServer::updateClients(QString msg, int length)
{
    emit updateServer(msg, length); // 通知在ui上显示

    for (int i = 0; i < tcpClientSocketList.count(); ++i)
    {
        QTcpSocket* tcpSocket = tcpClientSocketList.at(i);
        qDebug() << tcpSocket->socketDescriptor();

        if (tcpSocket->write(msg.toLatin1(), length) != length)
        {
            continue;
        }
    }
}

void TcpServer::onDisconnected(qintptr socketDescriptor)
{
    for (int i = 0; i < tcpClientSocketList.count(); ++i)
    {
        QTcpSocket* tcpSocket = tcpClientSocketList.at(i);
        if (tcpSocket->socketDescriptor() == socketDescriptor)
        {
            tcpClientSocketList.removeAt(i);
            return;
        }
    }
}
